<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="消息类型" prop="messageType">
        <el-select v-model="queryParams.messageType" placeholder="请选择消息类型" clearable style="width: 150px">
          <el-option
            v-for="dict in message_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="消息接收人编号" prop="receiverId">
        <el-input
          v-model="queryParams.receiverId"
          placeholder="请输入消息接收人编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['messageCenter:messageNotification:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['messageCenter:messageNotification:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['messageCenter:messageNotification:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['messageCenter:messageNotification:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->
    <!-- 操作和状态按钮 -->
    <div class="operation-status-buttons">
       <!-- 状态按钮（左侧） -->
        <div class="status-buttons">
          <!-- 循环渲染订单状态按钮 -->
          <div 
            class="status-btn"
            v-for="dict in message_status" 
            :key="dict.value"
            :class="{ active: String(selectedStatus) === String(dict.value) }"
            @click="handleClick(dict.value)"
          >
            {{ dict.label }}
            <!-- 使用类型转换并添加调试信息 -->
            <span class="count-badge">
              ({{ dict.value === '0' || dict.value === 0 ? unreadCount : dict.value === '1' || dict.value === 1 ? readCount : 0 }})
            </span>
          </div>
        </div>
        
        <!-- 操作按钮（右侧） -->
        <div class="operation-buttons">
          <el-button 
            type="primary" 
            plain 
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['messageCenter:messageNotification:remove']"
          >删除选中</el-button>
          <el-button 
            type="primary" 
            plain 
            :disabled="multiple"
            @click="handleMarkAsRead"
            v-hasPermi="['messageCenter:messageNotification:edit']"
          >标记为已读</el-button>
          <el-button 
            type="primary"
            @click="handleAllRead"
            v-hasPermi="['messageCenter:messageNotification:edit']"
          >全部已读</el-button>
          <el-button 
            type="primary"
            @click="handleAllDelete"
            v-hasPermi="['messageCenter:messageNotification:remove']"
          >全部删除</el-button>
        </div>
    </div>
   
    <el-table v-loading="loading" :data="messageNotificationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="消息内容" align="center" prop="content" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="消息类型" align="center" prop="messageType">
        <template #default="scope">
          <dict-tag :options="message_type" :value="scope.row.messageType"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="消息接收人编号" align="center" prop="receiverId" />
      <el-table-column label="状态(0:未读 1:已读)" align="center" prop="status" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['messageCenter:messageNotification:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['messageCenter:messageNotification:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改消息通知对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="messageNotificationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="消息内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="消息类型" prop="messageType">
          <el-select v-model="form.messageType" placeholder="请选择消息类型">
            <el-option
              v-for="dict in message_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消息接收人编号" prop="receiverId">
          <el-input v-model="form.receiverId" placeholder="请输入消息接收人编号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MessageNotification">
import { listMessageNotification, getMessageNotification, delMessageNotification, addMessageNotification, updateMessageNotification } from "@/api/messageCenter/messageNotification"
import { ref, reactive, computed } from 'vue'

const { proxy } = getCurrentInstance()
const { message_type, message_status } = proxy.useDict('message_type', 'message_status')

const messageNotificationList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangeCreateTime = ref([])
//消息状态
// 记录当前选中的状态（默认选中"未读"，对应值0）
const selectedStatus = ref(0);

// 存储所有消息的未读和已读总数
const allUnreadCount = ref(0)
const allReadCount = ref(0)

// 计算未读和已读消息数量（使用总数）
const unreadCount = computed(() => allUnreadCount.value)
const readCount = computed(() => allReadCount.value)

// 获取所有消息的统计数量
async function getMessageStats() {
  try {
    // 创建不限制分页的查询参数，但保留其他过滤条件
    const statsQuery = {
      ...queryParams.value,
      pageNum: 1,
      pageSize: 9999, // 使用一个很大的值获取所有数据
      status: null // 不按状态过滤，获取所有消息
    }
    
    const response = await listMessageNotification(statsQuery)
    allUnreadCount.value = response.rows.filter(item => item.status === 0).length
    allReadCount.value = response.rows.filter(item => item.status === 1).length
  } catch (error) {
    console.error('获取消息统计失败:', error)
  }
}

// 点击按钮触发的函数（接收传递的值）
const handleClick = (value) => {
  // 更新选中状态
  selectedStatus.value = value;
  // 执行后续逻辑（如查询、筛选等）
  queryParams.value.status = value
  console.log('当前选中的值：', value);
  // 可在这里调用接口或其他业务函数
  getList()
};
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    content: null,
    createTime: null,
    messageType: null,
    receiverId: null,
    status: 0, // 默认查询未读消息
  },
  rules: {
    title: [
      { required: true, message: "标题不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "消息内容不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询消息通知列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0]
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1]
  }
  
  // 先获取当前页数据
  listMessageNotification(queryParams.value).then(response => {
    messageNotificationList.value = response.rows
    total.value = response.total
    loading.value = false
    
    // 然后更新统计数据
    getMessageStats()
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    content: null,
    createTime: null,
    messageType: null,
    receiverId: null,
    status: null,
    extraField1: null,
    extraField2: null
  }
  proxy.resetForm("messageNotificationRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = []
  proxy.resetForm("queryRef")
  // 重置状态筛选
  queryParams.value.status = null
  selectedStatus.value = 0
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加消息通知"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getMessageNotification(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改消息通知"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["messageNotificationRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMessageNotification(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMessageNotification(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  // const _ids = row?.id || ids.value
  const _title = row?.title || ids.value
  proxy.$modal.confirm('是否确认删除消息通知标题为"' + _title + '"的数据项？').then(function() {
    return delMessageNotification(_title)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 标记为已读操作 */
function handleMarkAsRead() {
  if (ids.value.length === 0) {
    proxy.$modal.msgError('请选择要标记的消息')
    return
  }
  proxy.$modal.confirm('是否确认将选中的消息标记为已读？').then(function() {
    // 这里需要调用标记为已读的API，使用更新API
    const updatePromises = ids.value.map(id => {
      return updateMessageNotification({ id, status: 1 })
    })
    return Promise.all(updatePromises)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("标记成功")
  }).catch(() => {})
}

/** 全部已读操作 */
function handleAllRead() {
  proxy.$modal.confirm('是否确认将所有消息标记为已读？').then(function() {
    // 创建不限制分页的查询参数
    const allQuery = {
      pageNum: 1,
      pageSize: 9999,
      status: 0 // 只查询未读消息
    }
    // 先获取所有未读消息
    return listMessageNotification(allQuery)
  }).then(response => {
    if (response.rows.length === 0) {
      proxy.$modal.msgSuccess("没有未读消息需要标记")
      return Promise.reject()
    }
    // 批量更新所有未读消息为已读
    const updatePromises = response.rows.map(item => {
      return updateMessageNotification({ id: item.id, status: 1 })
    })
    return Promise.all(updatePromises)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("全部标记成功")
  }).catch(() => {})
}

/** 全部删除操作 */
function handleAllDelete() {
  proxy.$modal.confirm('是否确认删除所有消息？此操作不可撤销！').then(function() {
    // 创建不限制分页的查询参数
    const allQuery = {
      pageNum: 1,
      pageSize: 9999
    }
    // 先获取所有消息ID
    return listMessageNotification(allQuery)
  }).then(response => {
    if (response.rows.length === 0) {
      proxy.$modal.msgSuccess("没有消息需要删除")
      return Promise.reject()
    }
    // 批量删除所有消息
    const allIds = response.rows.map(item => item.id)
    return delMessageNotification(allIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("全部删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('messageCenter/messageNotification/export', {
    ...queryParams.value
  }, `messageNotification_${new Date().getTime()}.xlsx`)
}

// 初始化时获取数据和统计信息
getMessageStats()
// 由于queryParams已经设置了默认状态为0，这里直接调用getList即可
getList()
</script>

<style scoped>
  .operation-status-buttons {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .operation-buttons {
    display: flex;
    gap: 10px;
  }

  .status-buttons {
    display: flex;  /* 横向排列 */
    gap: 12px;      /* 按钮之间的间距 */
    padding: 5px 5px;
    background-color: #F2F2F2;
    width: 220px;
  }

.status-btn {
  /* 基础样式 */
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: black;  /* 未选中文字颜色 */
  transition: all 0.2s;  /* 过渡动画 */
  display: flex;
  align-items: center;
  gap: 4px;
}

.count-badge {
  font-size: 12px;
  color: black;
  font-weight: 500;
  padding: 2px 6px;
  border-radius: 10px;
  margin-left: 5px;
}

/* 选中样式（通过active类控制） */
.status-btn.active {
  background: white;  /* 选中背景色（自定义） */
  color: black;          /* 选中文字颜色 */
  /* 可选：添加阴影增强选中效果 */
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

/* 鼠标悬停样式 */
.status-btn:not(.active):hover {
  background: #e9e9e9;  /* 未选中时的悬停背景 */
}
</style>
